package com.example.demo01.demo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.demo01.R;
import com.example.demo01.adapter.HttpResultAdapter;
import com.example.demo01.entity.BxiaoQiGroup;
import com.example.demo01.entity.ResultData;
import com.example.demo01.entity.UserDemo;
import com.example.demo01.fragments.TitleFragment;
import com.example.demo01.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpDemo extends AppCompatActivity {
    private final String BaseURL = "http://bxiaoqi.top:81";
    private String token;
    private List<BxiaoQiGroup> items;
    private int current = 0;

    private MyHandler myhandler = new MyHandler();
    public static final int LOGIN = 1; //. 登录
    public static final int GET_GROUP = 2; //. 获取分组列表

    Utils utils = new Utils(this);
    private ListView lv_result;
    private TextView tv_http_text;

    private Button btn_http_native, btn_http_okhttp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_http);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //. 添加标题
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fl_title, TitleFragment.newInstance(getResources().getString(R.string.HttpDemo)))
                .commit();

        initView();
    }

    //. 初始化视图
    private void initView() {
        btn_http_native = findViewById(R.id.btn_http_native);
        btn_http_okhttp = findViewById(R.id.btn_http_okhttp);
        tv_http_text = findViewById(R.id.tv_http_text);
        lv_result = findViewById(R.id.lv_result);

        addListener();
    }

    //. 添加点击事件
    private void addListener() {
        //- 原生发送网络请求
        btn_http_native.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                utils.showToast("发送请求");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //. 创建URL对象
                            URL getUrl = new URL(BaseURL + "/group/getGroupList");
                            //. 打开连接
                            HttpURLConnection getConn = (HttpURLConnection) getUrl.openConnection();
                            //. 设置请求方式
                            getConn.setRequestMethod("GET");

                            //. 处理响应
                            //. 获取响应码
                            int responseCode = getConn.getResponseCode();
                            //. 判断响应码是否为200，200表示成功
                            if (responseCode == HttpURLConnection.HTTP_OK) {
                                //. 获取输入流
                                InputStream inputStream = getConn.getInputStream();
                                //. 定义BufferedReader输入流来读取URL的响应 ，这里设置编码
                                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                                //. 读取内容
                                StringBuilder response = new StringBuilder();

                                String line;
                                //. 循环读取数据
                                while ((line = reader.readLine()) != null) {
                                    response.append(line);
                                }
                                //. 关闭流
                                reader.close();

                                Log.d("GET Response", response.toString());

                                //. 处理响应数据（如解析 JSON）
                                TypeReference<ResultData<List<BxiaoQiGroup>>> res = new TypeReference<>() {
                                };
                                ResultData<List<BxiaoQiGroup>> resData = JSON.parseObject(response.toString(), res);
                                Message msg = myhandler.obtainMessage();
                                msg.what = GET_GROUP;
                                msg.obj = resData.getData();
                                myhandler.sendMessage(msg);

                            } else {
                                Log.e("GET Error", "请求失败，状态码：" + responseCode);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        });

        //- OkHttp发送POST请求
        btn_http_okhttp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpClient client = new OkHttpClient();
                //. 创建FormBody对象,用来储存表单数据
                RequestBody formBody = new FormBody.Builder()
                        .add("username", "北小齐用户")
                        .add("password", "kui1465583644.")
                        .build();

                //. 创建Request对象
                Request request = new Request.Builder()
                        .url(BaseURL + "/user/login")
                        .post(formBody) //. 使用POST方法发送表单数据
                        .build();

                //. 发送请求
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {
                            ResultData<String> responseData = null;
                            //. 解析响应数据
                            TypeReference<ResultData<String>> typeString = new TypeReference<ResultData<String>>() {
                            };
                            if (response.body() != null) {
                                responseData = JSON.parseObject(response.body().string(), typeString);
                            }

                            Message msg = myhandler.obtainMessage();
                            msg.what = LOGIN;
                            msg.obj = responseData.getData();
                            myhandler.sendMessage(msg);
                        }
                    }
                });

            }
        });
    }


    class MyHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == LOGIN) {
                handleLogin((String) msg.obj);

            } else if (msg.what == GET_GROUP) {
                handleGroup((List<BxiaoQiGroup>) msg.obj);

            }
        }
    }

    private void handleLogin(String token) {
        Log.i("token", "token:" + token);
        if (!token.isEmpty()) {
            tv_http_text.setText("登录成功token为：" + token);
        }

    }

    private void handleGroup(List<BxiaoQiGroup> list) {
        items = list;
        Log.i("item", "item:" + items.get(0).toString());

        HttpResultAdapter adapter = new HttpResultAdapter(items, HttpDemo.this);

        lv_result.setAdapter(adapter);

        lv_result.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(HttpDemo.this, IntentTestPage.class);
                BxiaoQiGroup item = adapter.getItem(position);
                UserDemo user = new UserDemo(item.getId(), item.getName(), item.getCreatedate().toString());
                intent.putExtra("user", user);
                startActivity(intent);
            }
        });
    }
}